package common

import "time"

type GameTimer struct {
	timer    *time.Timer
	startAt  time.Time     // 启动时间
	duration time.Duration // 时长
	jobChan  chan func()   // 任务队列
	job      func()        // 执行的任务
	running  bool
}

func NewTimer(queue bool) *GameTimer {
	if queue { // 队列
		return &GameTimer{jobChan: make(chan func(), 1)}
	}
	return &GameTimer{}
}

func (t *GameTimer) Start(d time.Duration, f func()) {
	if t.timer == nil {
		t.timer = time.AfterFunc(d, t.timeout)
	} else {
		t.timer.Reset(d)
	}
	t.startAt = time.Now()
	t.duration = d
	t.job = f
	t.running = true
}

// 加时
func (t *GameTimer) AddTime(d time.Duration) bool {
	if !t.running {
		return false
	}
	t.duration += d
	t.timer.Reset(t.Left())
	return true
}

func (t *GameTimer) timeout() {
	t.running = false
	if t.job == nil {
		return
	}
	if t.jobChan == nil {
		t.job()
	} else {
		t.jobChan <- t.job
	}
}

func (t *GameTimer) Do(f func()) {
	if t.jobChan != nil && f != nil {
		t.jobChan <- f
	}
}

func (t *GameTimer) GetJob() chan func() {
	return t.jobChan
}

func (t *GameTimer) Stop() {
	t.running = false
	if t.timer != nil {
		t.timer.Stop()
	}
}

func (t *GameTimer) Left() time.Duration {
	if t.running {
		return t.startAt.Add(t.duration).Sub(time.Now())
	}
	return 0
}

func (t *GameTimer) Running() bool {
	return t.running
}
